package org.java.Jwt;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.UUID;

/**
 * @Description Jwt DEMO
 * @Date 2024/8/28 10:35
 * @Created by 10574
 */
public class JwtDemo {
    private static final String ISSUER = "ZYR";
    private static final String SECRET_KEY = "123";

    public static void main(String[] args) {
        // 生成JWT
        final String jwt = createJwt("123");
        System.out.println("jwt:" + jwt);
        // 解析JWT
        final String subject = parseJwt(jwt);
        System.out.println("subject:" + subject);
    }

    /**
     * 创建JWT
     * @param payload 负载
     * @return jwt
     */
    public static String createJwt(String payload) {
        return Jwts.builder()
                .setId(UUID.randomUUID().toString())
                .setSubject("123")
                .setIssuer(payload)
                .setIssuedAt(new Date())
                .setExpiration(plusDayFromNow(1))
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY.getBytes())
                .claim("address", "haimen")
                .compact();
    }

    public static String parseJwt(String jwt) {
        return Jwts.parser()
                .setSigningKey(SECRET_KEY.getBytes())
                .parseClaimsJws(jwt)
                .getBody()
                .getSubject();
    }
    private static Date plusDayFromNow(long day) {
        final LocalDate localDate = LocalDate.now().plusDays(day);
        return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
    }
}
